package cn.shiwei.dome._2_work;

import cn.shiwei.dome._1_hello.Hello;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

public class ConsumerTwo {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        Connection connection = connectionFactory.newConnection();

        // 创建通道
        Channel channel = connection.createChannel();

        // 在消费者类中可以设置, 最大同时消息处理数量
        channel.basicQos(1);

        // 这个结构表示为建立了一个成员内部类, 并覆写方法
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("时间: " + new Date());
                System.out.println("consumerTag: " + consumerTag);
                System.out.println("交换机: " + envelope.getExchange());
                System.out.println("deliveryTag: " + envelope.getDeliveryTag());
                System.out.println("routingKey: " + envelope.getRoutingKey());
                System.out.println("信息: " + new String(body));

                channel.basicAck(
                        envelope.getDeliveryTag(), // 要处理的信息唯一id
                        false // 不开启批量签收
                );
            }
        };

        // 消费(就是监听队列)
        channel.basicConsume(
                Work.QUEUE_HELLO_NAME, // 队列名
                false, // 关闭自动签收
                consumer
        );


    }
}
